/**
 * @name fetchSse
 * @description 使用fetch来实现sse,使用的时候传入url和options
 * @param url
 * @param options
 * @returns //reader是流读取器，decoder是解码器，reader里面包含value和done
 * @example
 * //api封装
 * //sse
export const getFetchSse = () => {
  return fetchReader("/stream", {
    method: "GET",
  });
};

  //获取数据及处理
    getFetchSse().then(async ({ reader, decoder }) => {
      // 循环读取流数据
      let done = false;
      while (!done) {
        // 读取流中的一部分
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        if (!done) {
          let buffer = "";
          buffer = decoder.decode(value, { stream: true });
          const parsedMessage = JSON.parse(buffer);
          console.log({ value: parsedMessage, status: done }); // 输出每次的内容
        }
      }
    });
 * 
 * 
 */
const target = 'http://182.43.22.191:30888';
const fetchReader = (url: string, options: RequestInit = {}) => {
  const decoder = new TextDecoder();

  return new Promise<{
    reader: ReadableStreamDefaultReader<Uint8Array>;
    decoder: TextDecoder;
  }>((resolve, reject) => {
    fetch(`${target}${url}`, options)
      .then((response) => {
        const reader = response.body?.getReader();
        if (reader) {
          resolve({ reader, decoder });
        } else {
          reject(new Error('Response body is null'));
        }
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export { fetchReader };
